import { useState, Suspense, useEffect, useRef } from 'react';
import { SearchOutlined, ExpandOutlined, BellOutlined, DownOutlined } from '@ant-design/icons';
import "../assets/css/index.scss"
import {
    TeamOutlined,
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    UserOutlined
} from '@ant-design/icons';
import FullScreen from '../components/FullScreen';

import { Layout, Menu, theme, Button, Breadcrumb, Tabs, Dropdown, Space, Select, Flex } from 'antd';
import { useNavigate, Outlet, useLocation, Link } from "react-router-dom"
const { Header, Content, Footer, Sider } = Layout;
function getItem(label, key, icon, children) {
    return {
        key,
        icon,
        children,
        label,
    };
}
const items = [

    {
        key: "key1",
        icon: <UserOutlined />,
        label: "运营",
        children: [
            {
                key: "/",//路径
                label: "控制台",
            },
            {
                key: "/goodscount",
                label: "商品统计",

            },
            {
                key:"/usercount",
                label:"用户统计"
            },
            {
                key:"/trade",
                label:"交易统计"
            }
        ]
    },
    {
        key: "key2",
        icon: <UserOutlined />,
        label: "商品",
        children: [
            {
                key: "/goodsmanger",
                label: "商品管理",
            },
            {
                key: "/goodstype",
                label: "商品分类",
            },
            {
                key: "/goodsspecs",
                label: "商品规格",
            },
            {
                key: "/goodsevaluate",
                label: "商品评价",
            }
        ]
    },
    {
        key: "key3",
        icon: <UserOutlined />,
        label: "订单",
        children: [
            {
                key: "/goodsorder",
                label: "商品订单",
            },
           
        ]
    },
    {
        key: "key4",
        icon: <UserOutlined />,
        label: "用户",
        children: [
            {
                key: "/usermanage",
                label: "用户管理",
            },
            {
                key: "/userlable",
                label: "用户标签",
            },
            {
                key: "/userrank",
                label: "用户等级",
            },
            {
                key: "/usergroups",
                label: "用户分组",
            },
           
        ]
    },
    {
        key: "key5",
        icon: <UserOutlined />,
        label: "文章",
        children: [
            {
                key: "/articletype",
                label: "文章分类",
            },
            {
                key: "/articlemanger",
                label: "文章管理",
            },
           
        ]
    },
];

const downlist = [
    {
        key: '/',
        label: <Link to="/">首页</Link>
    },
    {
        key: "/my",
        label: <Link to="/my"> 个人中心</Link>
    },
    {
        key: "/buju",
        label: <Link to="/buju">布局设置 </Link>
    },
    {
        key: "/login",
        label: <Link to="/login">退出</Link>
    }

];


const onChange = (value) => {
    console.log(`selected ${value}`);
};
const onSearch = (value) => {
    console.log('search:', value);
};







const Index = () => {
    const route = useLocation()//获取本地页面的所有的信息
    const navigate = useNavigate()
    const [collapsed, setCollapsed] = useState(false);
    const { token: { colorBgContainer, borderRadiusLG } } = theme.useToken();

    const [openKey, setOpenKey] = useState([""])//展示那个模块
    const [path, setPath] = useState([""])
    const [navitem, setNavitem] = useState([
        {
            title: <a href='/'>首页</a>,
        },
        {
            title: <a href='/'>运营</a>,
        },
        {
            title: "控制台",
        }

    ])
    const openFun = (res) => {
        setOpenKey([res[res.length - 1]])
    }
    const clickItem = (res) => {//单机左侧菜单页面跳转************************************************************
        setPath([res.key])
        navigate(res.key)
        // console.log(res.key);
        items.map(item => {
            item.children.map(sonitem => {
                if (res.key == sonitem.key) {
                    setNavitem(pre => {
                        // console.log(pre);
                        setValue(sonitem.label)
                        pre[pre.length - 2].title = <Link to={item.children[0].key}>{item.label}</Link>
                        pre[pre.length - 1].title = sonitem.label
                        return [...pre]
                    })
                    setActiveKey(res.key)
                    let index = itemss.findIndex(item => res.key == item.key)
                    console.log(index);
                    if (index == -1) {
                        setItemss(arry => {
                            arry.push({
                                label: sonitem.label,
                                key: res.key
                            })
                            return [...arry]
                        })
                    }
                }

            })
        })




    }

    const routeFun = () => {

        items.map(item => {
            item.children.map(sonitem => {
                if (route.pathname == sonitem.key) {
                    // console.log(sonitem.label);
                    setItemss([{
                        label: sonitem.label,
                        key: sonitem.key,
                    }])

                    setActiveKey(sonitem.key);
                    setOpenKey([item.key])// 打开选中的父类
                    setPath([sonitem.key])

                    setNavitem(pre => {
                        // console.log(pre);

                        pre[pre.length - 2].title = <Link to={item.children[0].key}>{item.label}</Link>
                        pre[pre.length - 1].title = sonitem.label
                        return [...pre]
                    })

                }
            })
        })
    }

    useEffect(() => {
        setActiveKey(route.pathname)
        routeFun()
        filterItems()
    }, [])

    const clickNav = (e) => {
        let attr = e.target.getAttribute("href")
        console.log(attr);
        // setPath(attr)
        // setActiveKey(attr)
        clickItem({ key: attr })
    }



    let initialItems = [
        {
            label: '控制台',
            key: '/',
        },

    ]
    const [activeKey, setActiveKey] = useState(initialItems[0].key);
    const [itemss, setItemss] = useState(initialItems);
    const newTabIndex = useRef(0);
    const onChange = (newActiveKey) => {
        setActiveKey(newActiveKey);
    };
    // const add = () => {
    //     const newActiveKey = `newTab${newTabIndex.current++}`;
    //     const newPanes = [...itemss];
    //     newPanes.push({
    //         label: 'New Tab',
    //         children: 'Content of new Tab',
    //         key: newActiveKey,
    //     });
    //     setItemss(newPanes);
    //     setActiveKey(newActiveKey);
    // };
    const remove = (targetKey) => {
        let newActiveKey = activeKey;
        let lastIndex = -1;
        itemss.forEach((item, i) => {
            if (item.key === targetKey) {
                lastIndex = i - 1;
            }
        });
        const newPanes = itemss.filter((item) => item.key !== targetKey);
        if (newPanes.length && newActiveKey === targetKey) {
            if (lastIndex >= 0) {
                newActiveKey = newPanes[lastIndex].key;
            } else {
                newActiveKey = newPanes[0].key;
            }
        }
        setItemss(newPanes);
        setActiveKey(newActiveKey);
    };
    const onEdit = (targetKey, action) => {
        if (action === 'add') {
            // add();
        } else {
            remove(targetKey);
        }
    };
    const onTabClick = (targetKey) => {//单机tab选项卡
        items.map(item => {
            item.children.map(sonitem => {
                if (targetKey == sonitem.key) {
                    setValue(sonitem.label)
                    setOpenKey([item.key])
                    setNavitem(pre => {
                        // console.log(pre);

                        pre[pre.length - 2].title = <Link to={item.children[0].key}>{item.label}</Link>
                        pre[pre.length - 1].title = sonitem.label
                        return [...pre]
                    })

                }
            })
        })
        setPath(targetKey)
        navigate(targetKey)

    }
    const onClickitem = ({ key }) => {
        if (key == "/") {
            setOpenKey(["key1"])
            setPath("/")
            clickItem({ key: "/" })
        }
    }

    //搜索事件
    const [options, setOptions] = useState([])
    const filterItems = () => {
        let arry = []
        items.map(item => {
            item.children.map(sonitem => {
                arry.push({
                    value: sonitem.key,
                    label: sonitem.label
                })
            })
        })
        setOptions(arry)
    }
    const onselectChange = (value) => {
        clickItem({ key: value })
        onTabClick(value)
    }
    const [value, setValue] = useState("")
    return (
        <Layout
            style={{
                minHeight: '100vh',
            }}
        >

            <Sider
                style={{
                    overflow: 'auto',
                    height: '100vh',
                    position: 'fixed',
                    left: 0,
                    top: 0,
                    bottom: 0,
                }}
                trigger={null} collapsible collapsed={collapsed}>
                <div className="demo-logo-vertical" />
                <Menu
                    theme="dark"
                    mode="inline"
                    selectedKeys={path}
                    openKeys={openKey}
                    items={items}
                    onOpenChange={(e) => openFun(e)}
                    onClick={(e) => clickItem(e)}
                />
            </Sider>
            <Layout 
             style={{
                marginLeft: 200,
              }}>
                <Header
                    style={{
                        padding: "0 16px 0 16px",
                        position: "sticky",
                        top: 0,
                        zIndex: 2,
                        width: "100%",
                        background: colorBgContainer,
                    }}>
                    <Flex justify="space-between">
                        <Flex>
                            <Button
                                type="text"
                                icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                                onClick={() => setCollapsed(!collapsed)}
                            />
                            <Breadcrumb
                                className='breadcrumb'
                                items={navitem}
                                onClick={(e) => { clickNav(e) }}
                            >


                            </Breadcrumb>


                        </Flex>
                        <Flex>
                            <div className='tapright'>
                                {/* 搜索*******************************   */}
                                <Select
                                    showSearch
                                    placeholder="Select a person"

                                    optionFilterProp="label"
                                    onChange={onselectChange}
                                    onSearch={onSearch}
                                    options={options}
                                />
                                {/* 图标************************************ */}
                                <FullScreen></FullScreen>
                                <BellOutlined />
                                <Dropdown
                                    menu={{
                                        items: downlist,
                                        onClick: onClickitem
                                    }}
                                    trigger={['click']}
                                >
                                    <a onClick={(e) => e.preventDefault()}>
                                        <Space>
                                            demo
                                            <DownOutlined />
                                        </Space>
                                    </a>
                                </Dropdown>
                            </div>
                        </Flex>
                    </Flex>
                    <Tabs
                    style={{background:"#f5f5f5",paddingTop:"10px"}}
                     type="editable-card"
                        onChange={onChange}
                        activeKey={activeKey}
                        onTabClick={onTabClick}
                        onEdit={onEdit}
                        items={itemss}
                        hideAdd={true}
                    />

                </Header>
                <Content style={{ margin: '16px', paddingTop:"40px" }}>
                    {/* <p>使用一个面包屑</p> */}








                    <Suspense fallback={<div>加载中...</div>}>
                        <Outlet></Outlet>
                    </Suspense>

                </Content>

                <Footer style={{ textAlign: 'center' }}>官网社区文档</Footer>
            </Layout>
        </Layout>
    );
};



export default Index;